package fragment;

import java.util.Iterator;
import java.util.Vector;

import entities.FragmentDirectory;
import entities.MMMEDirectory;

public class ContactHandler extends QuasiComponentContactHandler{
	
	private Fragment self;
	private final MMMEDirectory elemDir;
	private final FragmentDirectory fragDir;
	
	public ContactHandler(MMMEDirectory elemDir, FragmentDirectory fragDir) {
		super();
		this.elemDir = elemDir;
		this.fragDir = fragDir;
	}
	
	public void linkReference(Fragment ref){		//needed for the moment because of the implementation of MAY
		self=ref;									//must be called at the initialization of the Fragment
	}
	
	@Override
	public Fragment getFragment(String id) {
		return fragDir.getFragment(id);
	}
	
	@Override
	public Vector<Fragment> findAllPotentialGenerators(String mmme) {
		Vector<Fragment> res=new Vector<Fragment>();
		Iterator<Fragment> it=(new Vector<Fragment>(fragDir.getListeFragment())).iterator();
		while (it.hasNext()){
			Fragment temp=it.next();
			if (temp.getGenerationCapabilities().contains(mmme))
				res.add(temp);
		}
		return res;
	}

	@Override
	public void informOfGeneration() {
		elemDir.registerNewGenerator(self);
	}

	@Override
	public void informStoppingGeneration() {
		elemDir.removeGenerator(self);
		
	}

	@Override
	public boolean isElementPresent(String mmme) {
		return elemDir.contains(mmme);
	}

	@Override
	public boolean isMMMEGivenByUser(String mmme) {
		return elemDir.isGivenByUser(mmme);
	}
	
	@Override
	public void informOfRelease(String mmme) {
		if(elemDir.getMMMEList().containsKey(mmme))
			elemDir.getMMMEList().get(mmme).removeReservator(self);
		
	}

	@Override
	public void informOfReservation(String mmme) {
		if(elemDir.getMMMEList().containsKey(mmme))
			elemDir.getMMMEList().get(mmme).addReservator(self);
		
	}
	
	@Override
	public boolean nobodyNeed(String mmme) {
		return fragDir.nobodyNeed(mmme);
	}
	
	@Override
	public void start() {
		fragDir.addFragment(self);
	}

	

	



}
